#!/usr/bin/env python
# Runs a child program which accepts one line of input at a time and produces
# one line of output for each line of input.

import string
import subprocess

class LineByLine:
  def __init__(self, cmd):
    self.child = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE)
    # Buffer of output read from the child.
    self.output = ""

  def push(self, line):
    self.child.stdin.write(line + '\n')

  def _grab_output(self):
    while True:
      # TODO: this deadlocks
      data = self.child.stdout.read(1000)
      if data == '':
        return
      self.output += data

  def has_output(self):
    self._grab_output()
    return string.find(self.output, '\n') >= 0

  def pull(self):
    """ Returns the next line of output. Dies if there isn't any. """
    self._grab_output()
    newline = string.find(self.output, '\n')
    assert newline >= 0
    line = self.output[0:newline]
    self.output = self.output[newline + 1:]

